<style>
body {
  min-width: 360px;
  overflow-x: hidden;
}
#rename-this_newName {
  width: 80%;
  float: left;
}
#rename-this_restore {
  width: 18%;
  float: right;
}
</style>

<p>
	<input type="text" id="rename-this_newName" onkeyup="rename_this_doit(this.value)"/>
	<input type="button" id="rename-this_restore" value="Reset" onclick="rename_this_reset()"/>
</p>

<div style="clear:both"></div>

<script>

var bg = chrome.extension.getBackgroundPage();
var tabNames = bg.tabNames;
var tabRestore = bg.tabRestore;

function rename_this_doit(newName)
{	
	chrome.tabs.getSelected(null, function(tab)
	{
		// remember what it was orginally called
		if(!tabNames[tab.id] && tabNames[tab.id] != '')
			tabRestore[tab.id] = tab.title;
		
		// remember what we want it to be called
		tabNames[tab.id] = newName;
	});
	
	// rename it
	chrome.tabs.executeScript(null, {code: 'document.title = "'+newName+'";'}, null);
}

function rename_this_reset()
{
	chrome.tabs.getSelected(null, function(tab)
	{
		// restore it
		chrome.tabs.executeScript(null, {code: 'document.title = "'+tabRestore[tab.id]+'";'}, null);
		document.getElementById("rename-this_newName").value = tabRestore[tab.id];
		
		// delete the cache so that this extension will not mess it up later
		tabNames[tab.id] = null;
	});
}

function onPopup()
{
	var field = document.getElementById("rename-this_newName");
	chrome.tabs.getSelected(null, function(tab)
	{
		// auto-fill the box with something smart
		field.value = tabNames[tab.id] ? tabNames[tab.id] : tab.title;
	});
	field.focus();
	//field.select();  // why doesn't this work in chrome?
}

onPopup();

</script>

